﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataWorks_Tools.LSTMDetails
{
    public class MinMaxScaler
    {
        public readonly Dictionary<string, (double Min, double Max)> scalerDict;

        public MinMaxScaler(string csvPath)
        {
            scalerDict = new Dictionary<string, (double, double)>();
            LoadScaler(csvPath);
        }

        private void LoadScaler(string csvPath)
        {
            using (var reader = new StreamReader(csvPath))
            {
                var header = reader.ReadLine(); // skip header
                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();
                    var parts = line.Split(',');

                    if (parts.Length >= 3)
                    {
                        string feature = parts[0];
                        double min = double.Parse(parts[1], CultureInfo.InvariantCulture);
                        double max = double.Parse(parts[2], CultureInfo.InvariantCulture);

                        scalerDict[feature] = (min, max);
                    }
                }
            }
        }

        // ✅ 单列归一化
        public double Normalize(double value, string feature)
        {
            if (!scalerDict.ContainsKey(feature)) throw new Exception($"Feature '{feature}' not found.");
            var (min, max) = scalerDict[feature];
            return (value - min) / (max - min);
        }

        // ✅ 多列归一化（传入特征字典）
        public float[] Normalize(Dictionary<string, double> inputFeatures)
        {
            var normalized = new List<float>();
            foreach (var kv in scalerDict)
            {
                string feature = kv.Key;
                if (!inputFeatures.ContainsKey(feature))
                    throw new Exception($"Missing feature '{feature}' in input.");

                var value = inputFeatures[feature];
                var (min, max) = scalerDict[feature];
                float norm = (float)((value - min) / (max - min));
                normalized.Add(norm);
            }
            return normalized.ToArray();
        }

        // ✅ 单列反归一化
        public double Denormalize(double normalizedValue, string feature)
        {
            if (!scalerDict.ContainsKey(feature)) throw new Exception($"Feature '{feature}' not found.");
            var (min, max) = scalerDict[feature];
            return normalizedValue * (max - min) + min;
        }

        // 获取特征顺序（用于保持一致的输入顺序）
        public List<string> GetFeatureOrder() => new List<string>(scalerDict.Keys);
    }
}
